package sk.pitonak.mhd;

import java.util.ArrayList;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;

public class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener,
	ViewPager.OnPageChangeListener {
	private Context mContext;
	private ActionBar mActionBar;
	private ViewPager mViewPager;
	private ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

	private static final class TabInfo {
		public String clss;
		public Bundle args;

		public TabInfo(Class<?> clss, Bundle args) {
			this.clss = clss.getName();
			this.args = args;
		}
	}

	public TabsAdapter(FragmentActivity activity, ActionBar actionBar, ViewPager viewPager) {
		super(activity.getSupportFragmentManager());
		mContext = activity;
		mActionBar = actionBar;
		mViewPager = viewPager;
		mViewPager.setAdapter(this);
		mViewPager.setOnPageChangeListener(this);
	}

	public void addTab(String title, Class<?> clss, Bundle args) {
		mTabs.add(new TabInfo(clss, args));

		ActionBar.Tab tab = mActionBar.newTab();
		tab.setText(title);
		tab.setTabListener(this);
		mActionBar.addTab(tab);
	}

	public void addTab(int resId, Class<?> clss, Bundle args) {
		addTab(mContext.getString(resId), clss, args);
	}

	public void addTab(String title, Class<?> clss) {
		addTab(title, clss, null);
	}
	
	public void addTab(int resId, Class<?> clss) {
		addTab(mContext.getString(resId), clss, null);
	}

	@Override
	public int getCount() {
		return mTabs.size();
	}

	@Override
	public Fragment getItem(int position) {
		TabInfo tabInfo = mTabs.get(position);
		return Fragment.instantiate(mContext, tabInfo.clss, tabInfo.args);
	}

	@Override
	public void onPageSelected(int position) {
		mActionBar.setSelectedNavigationItem(position);
	}

	@Override
	public void onTabSelected(Tab tab) {
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrollStateChanged(int state) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTabUnselected(Tab tab) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabReselected(Tab tab) {
		// TODO Auto-generated method stub
		
	}

}
